import compareJsons from './compareJsons.js';
import store from "../store"
import fileManage from './fileManage.js'
import vuexSave from './vuexSave.js'

let fs = fileManage.fs,userDataPath = fileManage.userDataPath;
const getStartPages = ()=>{
	return new Promise(resolve => {
		// 先获取首页的json
		var indexPage = store.state.$pageList.filter(page=>page.pageCode === store.state.$appInfo.startPageId)
		compareJsons(indexPage).then(()=>{
			if (store.state.$appInfo.startType === 'tabbar') {
				fs.readFile({
					filePath: `${userDataPath}/${store.state.$appInfo.startPageId}.json`,
					encoding: 'utf8',
					success(res) {
						console.log('readFile-success',store.state.$appInfo.startPageId+'.json');
						var appMenus = JSON.parse(res.data)
						var tabbarPages = store.state.$pageList.filter(page=>appMenus.common.links.some(link=>link.pageId===page.pageCode))
						compareJsons(tabbarPages).then(()=>{
							resolve(appMenus)
						})
					},
					fail(res) {
						console.log('readFile-fail', res)
						resolve()
					}
				})
			} else if (appInfo.startType === 'singlePage') {
				resolve()
			}
		})
	})
}
export default () => {
	return new Promise(resolve => {
		fs.readFile({
			filePath: `${userDataPath}/pageList.json`,
			encoding: 'utf8',
			success(res) {
				console.log('readFile-success','pageList.json');
				vuexSave('$oldPageList', JSON.parse(res.data));
				getStartPages().then(appMenus=>{
					resolve(appMenus)
				})
			},
			fail(res) {
				console.log('readFile-fail', res)
				vuexSave('$oldPageList', []);
				getStartPages().then(appMenus=>{
					resolve(appMenus)
				})
			}
		})
	})
}
